package com.shanyue.handler;


import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


@RestController
public class Servletcode {

	@RequestMapping("/Servletcode")
	public String toCode(String action, HttpSession session, HttpServletResponse resp, HttpServletRequest req) throws IOException {
		System.out.println("-----------------------"+action);
		if ("all".equals(action)) {
			resp.setContentType("image/jpg");

			char[] code = {'2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
					'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
					'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

			BufferedImage rotateImage = new BufferedImage(100, 30, BufferedImage.TYPE_INT_ARGB);
			Graphics2D graphics = rotateImage.createGraphics();
			int qz = (int) (Math.random() * 255);
			int qz2 = (int) (Math.random() * 255);
			int qz3 = (int) (Math.random() * 155);
			graphics.setColor(new Color(0, qz3, 0));
			graphics.fillRect(0, 0, 120, 30);

			System.out.println(qz + "--" + qz2 + "--" + qz3);
			Font font = new Font("微软雅黑", Font.BOLD, 23);
			graphics.setFont(font);
			graphics.setColor(new Color(qz, qz2, qz3));
			for (int i = 0; i < 3; i++) {
				graphics.drawLine(0, 0, qz, qz2);
				graphics.drawLine(qz2, qz3, 0, 0);
				graphics.drawLine(0, qz3, qz, 0);

			}

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 4; i++) {

				int a = (int) (Math.random() * code.length);

				sb.append(code[a]);
			}
			System.out.println(sb);

			graphics.drawString(sb.toString(), 17, 25);

			session.setAttribute("code", sb.toString());

			ImageIO.write(rotateImage, "jpg", resp.getOutputStream());


		} else if ("codeajax".equals(action)) {
			String attribute2 = (String) session.getAttribute("code");
			String parameter2 = req.getParameter("codes");
			System.out.println(parameter2 + "+===" + attribute2);

			if (attribute2.toUpperCase().equals(parameter2.toUpperCase())) {
//				resp.getWriter().write("true");
				return "true";
			} else {
//				resp.getWriter().write("false");
				return "false";
			}


		}
		return "";

	}

	


}
